package com.alogic.ac.loader.aak;

import com.alogic.ac.AccessAppKey;
import com.alogic.load.Loader;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.Script;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.*;
import org.w3c.dom.Element;

import java.util.HashMap;

/**
 * 从脚本加载AAK
 *
 * @since 1.6.12.54 [20191219]
 */
public class AAKFromScript extends Loader.Abstract<AccessAppKey> {

    /**
     * 加载事件脚本
     */
    protected Logiclet onLoad = null;

    /**
     * 对象id
     */
    protected String aakObjectId = "$aak-object";
    protected String aakId = "$aak-id";

    @Override
    public void configure(Properties p){
        super.configure(p);
        aakObjectId = PropertiesConstants.getString(p,"aakObjectId",aakObjectId,true);
        aakId = PropertiesConstants.getString(p,"aakId",aakId,true);
    }

    @Override
    public void configure(Element e, Properties p) {
        Properties props = new XmlElementProperties(e,p);

        Element onLoadElem = XmlTools.getFirstElementByPath(e, "on-load");
        if (onLoadElem != null){
            onLoad = Script.create(onLoadElem, props);
        }

        configure(props);
    }

    @Override
    public AccessAppKey load(String id, boolean cacheAllowed) {
        AccessAppKey found = null;
        if (onLoad != null){
            LogicletContext logicletContext = new LogicletContext(Settings.get());
            try {
                XsObject doc = new JsonObject("root",new HashMap<String,Object>());
                logicletContext.SetValue(aakId,id);
                onLoad.execute(doc,doc, logicletContext, null);
                found = logicletContext.getObject(aakObjectId);
            }finally{
                logicletContext.removeObject(aakObjectId);
            }
        }
        return found;
    }
}
